#!/bin/bash
# step_concurrency_test.sh

HOST="localhost"
PORT="8888"
DURATION=30
CONCURRENT_LEVELS=(8000 10000)

echo "开始逐步并发测试..."

for conc in "${CONCURRENT_LEVELS[@]}"; do
    echo "测试并发数: $conc, 持续时间: ${DURATION}秒"
    
    count=0
    start_time=$(date +%s)
    end_time=$((start_time + DURATION))
    
    # 清空临时文件
    rm -f /tmp/nc_result.$$
    
    while [ $(date +%s) -lt $end_time ]; do
        for i in $(seq 1 $conc); do
            (
                if echo "test $(date +%s%N) conc=$conc" | nc -w 3 $HOST $PORT > /dev/null 2>&1; then
                    echo "success" >> /tmp/nc_result.$$
                else
                    echo "fail" >> /tmp/nc_result.$$
                fi
            ) &
            count=$((count + 1))
        done
        sleep 0.05
    done
    
    wait
    
    # 统计结果 - 修复这里的语法错误
    success=0
    fail=0
    if [ -f /tmp/nc_result.$$ ]; then
        success=$(grep -c "success" /tmp/nc_result.$$)
        fail=$(grep -c "fail" /tmp/nc_result.$$)
    fi
    
    total=$((success + fail))
    
    # 计算QPS和成功率 - 添加安全检查
    if [ $total -gt 0 ]; then
        success_rate=$(echo "scale=2; $success * 100 / $total" | bc)
        qps=$(echo "scale=2; $success / $DURATION" | bc)
    else
        success_rate=0
        qps=0
    fi
    
    echo "并发 $conc: 总请求=$total, 成功=$success, 失败=$fail, 成功率=${success_rate}%, QPS=${qps}"
    echo "----------------------------------------"
    
    # 如果成功率低于90%，停止测试
    if [ $total -gt 0 ] && [ $(echo "$success_rate < 90" | bc) -eq 1 ]; then
        echo "警告: 成功率低于90%，停止测试"
        break
    fi
    
    sleep 2
done

rm -f /tmp/nc_result.$$
